package com.alipay.zxy.alipayplugin.service;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.domain.AlipayTradeRefundModel;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.alipay.zxy.alipayplugin.config.AlipayConfig;
import com.alipay.zxy.alipayplugin.config.DefaultAlipayClientFactory;
import com.alipay.zxy.alipayplugin.message.response.AlipayTradeRefundDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author zxy
 */
@Slf4j
@Service
public class AlipayTradeRefundService extends BaseService {
    private final AlipayConfig alipayConfig;

    @Autowired
    public AlipayTradeRefundService(AlipayConfig alipayConfig) {
        this.alipayConfig = alipayConfig;
    }

    public AlipayTradeRefundDTO refund(AlipayTradeRefundModel alipayModel) throws AlipayApiException {
        //初始化请求类
        AlipayTradeRefundRequest alipayRequest = new AlipayTradeRefundRequest();
        alipayRequest = (AlipayTradeRefundRequest) getAlipayRequest(alipayRequest, alipayConfig, alipayModel);
        log.info("支付宝请求参数alipayRequest：{}", alipayRequest);
        //sdk请求客户端，已将配置信息初始化
        AlipayClient alipayClient = DefaultAlipayClientFactory.getInstance(alipayConfig);
        //因为是接口服务，使用exexcute方法获取到返回值
        AlipayTradeRefundResponse alipayResponse = alipayClient.execute(alipayRequest);
        log.info("alipayResponse:{}", JSONObject.toJSONString(alipayResponse));
        if (alipayResponse.isSuccess()) {
            log.info("统一收单交易退款接口调用成功");
            AlipayTradeRefundDTO alipayTradeRefundDTO = new AlipayTradeRefundDTO();
            alipayTradeRefundDTO.setBuyerLogonId(alipayResponse.getBuyerLogonId());
            alipayTradeRefundDTO.setBuyerUserId(alipayResponse.getBuyerUserId());
            alipayTradeRefundDTO.setGmtRefundPay(alipayResponse.getGmtRefundPay().getTime());
            alipayTradeRefundDTO.setOutTradeNo(alipayResponse.getOutTradeNo());
            alipayTradeRefundDTO.setRefundFee(alipayResponse.getRefundFee());
            alipayTradeRefundDTO.setTradeNo(alipayResponse.getTradeNo());
            alipayTradeRefundDTO.setSendBackFee(alipayResponse.getSendBackFee());
            return alipayTradeRefundDTO;
        } else {
            log.info("统一收单交易退款接口调用失败");
            return null;
        }
    }
}
